<template>
  <div class='container'>
    <el-card shadow="never">
        <!-- 搜索 -->
        <el-form :model="form" ref="form">
          <div class="filter-container">
            <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="关键字：" prop="keyword">
                  <el-input
                    @keyup.enter="hQuery"
                    style="width: 200px;"
                    placeholder="根据文章标题搜索"
                    class="filter-item"
                    v-model="form.keyword"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="状态：" prop="state">
                  <el-select
                    class="filter-item"
                    style="width: 200px;"
                    v-model="form.state"
                    clearable
                  >
                    <el-option
                      v-for="item in status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item>
                  <el-button
                    :loading="isLoading"
                    size="small"
                    type="primary"
                    @click="hQuery"
                  >搜索</el-button>
                  <el-button
                  size="small"
                  @click="hResetForm">清除</el-button>
                </el-form-item>
              </el-col>
              <el-button
              class="filter-item fr"
              size="small"
              style="margin-left: 10px;"
              @click="hAddComponey"
              type="success"
              icon="el-icon-edit"
              >新增技巧</el-button>
            </el-row>
          </div>
        </el-form>
        <!-- 搜索完成 -->
        <!-- 数据记录 -->
        <el-alert
          v-if="cResultTip"
          :title="cResultTip"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
      <!-- 数据记录完成 -->
      <!-- 数据列表 -->
        <el-table
          :data="articles"
          v-loading="isLoading"
          element-loading-text="给我一点时间"
          fit
          highlight-current-row
          style="width: 100%"
          border
        >
          <el-table-column align="center" type="index" label="序号" width="70">
          </el-table-column>
          <el-table-column align="center"  width="400" label="文章标题">
            <template slot-scope="scope">
              <span>{{scope.row.title}}</span>
              <i class="el-icon-film"
                v-if="scope.row.videoURL"
                style="color: red; caret-color: rgba(0,0,0,0); cursor: pointer"
                @click="hVideoURL(scope.row.videoURL)"
                ></i>
            </template>
          </el-table-column>
          <el-table-column label="阅读数">
            <template slot-scope="scope">
              <span>{{scope.row.visits}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="录入人">
            <template slot-scope="scope">
              <span>{{scope.row.username}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="录入时间">
            <template slot-scope="scope">
              <span>{{scope.row.createTime | parseTimeByString("{y}-{m}-{d} {h}:{i}:{s}")}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.state==1">已启用</span>
              <span v-else>已禁用</span>
            </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column
            align="center"
            label="操作"
            width="280"
          >
            <template slot-scope="scope">
              <el-button  type="text"  @click="hPreview(scope.row.id)">预览</el-button>
              <el-button type="text"  @click="hSwitchStatus(scope.row)">
                <span >{{scope.row.state ===0 ? '启用' : '禁用'}}</span>
              </el-button>
              <el-button type="text" :disabled="Boolean(scope.row.state)" @click="hEdit(scope.row.id)">修改</el-button>
              <el-button
                v-if="scope.row.status!='deleted'"
                type="text"
                :disabled="Boolean(scope.row.state)"
                @click="hDelete(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 数据列表完成 -->
        <!-- 分页 -->
        <div class="pagination" v-show="total">
          <div class="pages">
            <el-pagination
              background
              @size-change="hSizeChange"
              @current-change="hCurrentChange"
              :current-page="Number(form.page)"
              :total="Number(total)"
              :page-size="Number(form.pagesize)"
              :page-sizes="[10,20,30, 50]"
              layout="sizes, prev, pager, next, jumper"
            ></el-pagination>
          </div>
        </div>
        <!-- 分页完成 -->
        <!-- 发布编辑弹出层 -->
        <el-dialog :title="cTitle"
          :visible.sync="isShowDialog"
          v-if="isShowDialog"
          width='800px'
        >
        <ArticlesAdd
        @addorEdit="hAddorEdit"
        @close='hClose'
        :id='curCompanyId'
        ></ArticlesAdd>
        </el-dialog>
        <!-- 发布编辑弹出层结束 -->
        <!-- 预览弹出层 -->
        <el-dialog title="预览文章"
          v-if="previewShow"
          :visible.sync="previewShow"
          width='800px'
          >
          <h2>{{article.title}}</h2>
          <div style='margin-left: 10px'>{{article.createTime | parseTimeByString("{y}-{m}-{d} {h}:{i}:{s}")}} 超级管理员 <i class="el-icon-view"></i> {{article.visits}}</div>
          <div class="articlestyle" v-html="article.articleBody"></div>
        </el-dialog>
        <!-- 预览弹出层结束 -->
    </el-card>
    <!-- 视频播放 -->
    <!-- 外层的遮罩 v-if用来控制显示隐藏 点击事件用来关闭弹窗 -->
    <div class='mask' v-if='videoState == true' @click='hClosevide'></div>
    <!-- 弹窗 -->
    <div class="videomasks" v-if="videoState == true">
    <!-- 视频：h5的视频播放video -->
    <video :src='videoSrc' autoplay>
    您的浏览器不支持 video 标签。
    </video>
    </div>
  </div>
</template>

<script>
// 导入组件添加/编辑
import ArticlesAdd from './articles-add'
import { status } from '@/api/hmmm/constants'
import { list as getArticles, changeState, remove, detail } from '@/api/hmmm/articles.js'
export default {
  name: 'Article',
  components: {
    ArticlesAdd
  },
  data () {
    return {
      // 视频地址
      videoSrc: '',
      // 视频弹层
      videoState: false,
      // 列表数据
      articles: [],
      // 文章详情
      article: {},
      // 数据条数
      total: 0,
      // 加载菊花
      isLoading: false,
      // 区别于是否是编辑，还是添加
      curCompanyId: null,
      // 弹出层显示
      isShowDialog: false,
      previewShow: false,
      // 查询表单中的参数
      form: {
        state: null,
        keyword: '',
        page: 1,
        pagesize: 10
      }
    }
  },
  // 创建完毕,做一次查询
  created () {
    this.loadArticles()
  },
  computed: {
    status () {
      return status
    },
    cResultTip () {
      return `共 ${this.total} 条记录`
    },
    cTitle () {
      return this.curCompanyId ? '编辑技巧' : '添加技巧'
    }
  },
  methods: {
    // 确认按钮
    hAddorEdit () {
      this.isShowDialog = false
      this.loadArticles()
    },
    // 关闭按钮
    hClose () {
      this.isShowDialog = false
    },
    // 构建查询数据
    buildParams () {
      const paramsObj = {}
      const { page, pagesize, keyword, state } = this.form
      // 如果某一个参数是null,则axios就不会发这个参数
      // 如果某一个参数是""，axios是会发出这个参数
      paramsObj.page = page || null
      paramsObj.pagesize = pagesize || null
      paramsObj.keyword = keyword || null
      paramsObj.state = state === '' ? null : state
      return paramsObj
    },
    // 获取列表数据
    async loadArticles () {
      this.isLoading = true
      // 构建查询参数
      const paramsObj = this.buildParams()
      try {
        const { data: res } = await getArticles(paramsObj)
        // 获取数据给articles
        this.articles = res.items
        // 获取总条数
        this.total = res.counts

        this.isLoading = false
      } catch (err) {
        console.log(err)
        this.isLoading = true
      }
    },
    // 重置整个表单
    hResetForm () {
      // el 表单组件上有一个resetFields方法
      this.$refs.form.resetFields()
    },
    // 搜索信息
    hQuery () {
      // 重置页码
      this.form.page = 1
      // 重发请求
      this.loadArticles()
    },
    // 更改每页显示的条数
    hSizeChange (val) {
      this.form.pagesize = val

      if (this.form.page === 1) {
        this.loadArticles()
      }
    },
    // 点击某一个页码
    hCurrentChange (curPage) {
      this.form.page = curPage
      this.loadArticles()
    },
    // 新增按钮
    hAddComponey () {
      this.curCompanyId = ''
      this.isShowDialog = true
    },
    // 编辑按钮
    async hEdit (id) {
      this.curCompanyId = id
      this.isShowDialog = true
    },
    // 预览
    async hPreview (id) {
      this.previewShow = true
      try {
        const { data: res } = await detail({ id: id })
        console.log(res)
        this.article = res
      } catch (err) {
        console.log(err)
      }
    },
    // 启用、禁用
    hSwitchStatus (row) {
      const tip = '已成功' + (row.state ? '禁用' : '启用') + ', 是否继续?'
      this.$confirm(tip, '提示', {
        type: 'warning'
      })
        .then(() => {
          this.doSwitch(row)
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    async doSwitch (row) {
      var data = {
        id: row.id,
        state: Number(!row.state)
      }
      console.log(data)
      await changeState(data)
        .then(response => {
          this.$message.success('操作成功!')
          this.loadArticles(this.form)
        })
        .catch(response => {
          this.$message.error(status + '失败!')
        })
    },
    // 删除
    hDelete (userId) {
      this.$confirm('此操作将永久删除用户 ' + ', 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.doDelete(userId)
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    async doDelete (id) {
      try {
        await remove({ id: id })
        this.$message.success('成功删除了用户!')
        this.loadArticles()
      } catch (err) {
        this.$message.error('删除失败!')
      }
    },
    // 视频播放
    hVideoURL (VideoURL) {
      console.log(VideoURL)
      this.videoState = true
      this.videoSrc = VideoURL
    },
    // 关闭视频
    hClosevide () {
      this.videoState = false
    }
  }
}
</script>

<style scoped lang="css">
  .pagination {
  margin-top: 10px;
  float: right;
}
.mask{
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  right:0;
  z-index:2000;
  background-color: #000000;
    opacity: .3;
}
 /* 内容层 z-index要比遮罩大，否则会被遮盖 */
.videomasks{
    max-width: 1200px;
    position: fixed;
    left: 50%;
    top: 50%;
    z-index: 2001;
    transform: translate(-50%,-50%);
  }
.videomasks video{
    width: 800px;
    height: 600px;
}
.articlestyle {
    background-color: #f5f5f5;
    padding: 15px;
    margin-top: 10px;
    border-top: dashed 1px #cccccc;
}
</style>
